"use strict";

let canvas;
let gl;

const ms = 180; // 组成圆的划分三角形个数
let IsFocus = false;
const r = 0.1;
const c  = 90;
const center = [-0.3, 0.6]
let space = []
let matType = [];
// 画圆
// 半径r 面数m 度数c
function getCircleVertex(r, m, c) {
    var arr = [];
    var addAng = c / m;
    var angle = 0;
    for (var i = 0; i < m; i++) {
        arr.push(Math.sin(Math.PI / 180 * angle) * r, Math.cos(Math.PI / 180 * angle) * r, 0, 1.0);
        arr.push(0.0, 0.0, 0.0, 1.0);
        angle = angle + addAng;
        arr.push(Math.sin(Math.PI / 180 * angle) * r, Math.cos(Math.PI / 180 * angle) * r, 0, 1.0);
    }
    return arr;
}
const colors = [
    [1.0, 0.843, 0.0, 1.0], //金黄色
    [1.0, 0.647, 0.0, 1.0], //橙色
    [0.824, 0.412, 0.118, 1.0], //巧克力色
    [0.0, 0.0, 0.0, 1.0], //黑色
    [1.0, 0.0, 0.0, 1.0]//红色
];
let matLoc;

window.onload = function init() {
    canvas = document.getElementById("gl-canvas");
    gl = WebGLUtils.setupWebGL(canvas);
    if (!gl) {
        alert("WebGL isn't available");
    }

    gl.viewport(0, 0, canvas.width, canvas.height);
    gl.clearColor(1.0, 1.0, 1.0, 1.0);

    //  Load shaders and initialize attribute buffers

    let program = initShaders(gl, "vertex-shader", "fragment-shader");
    gl.useProgram(program);

    // Load the data into the GPU

    // 获取vPosition变量的存储位置
    let vPosition = gl.getAttribLocation(program, "vPosition");
    if (vPosition < 0) {
        console.log('Failed to get the storage location of vPosition');
        return;
    }

    // 获取u_transMat变量的存储位置
    var u_transMat = gl.getUniformLocation(program, "u_transMat");
    if (u_transMat < 0) {
        console.log('Failed to get the storage location of u_transMat');
        return;
    }

    // 获取u_FragColor变量的存储位置
    var u_FragColor = gl.getUniformLocation(program, 'u_FragColor');
    if (!u_FragColor) {
        console.log('Failed to get the storage location of u_FragColor');
        return;
    }

    var vertices = getCircleVertex(r, ms, c);
    center[2] = 1;
    var Tx = center[0];
    var Ty = center[1];
    var Tz = 0.0;
    mat4 = new Float32Array([
        0.0, 1.0, 0.0, 0.0,
        -1.0, 0.0, 0.0, 0.0,
        0.0, 0.0, 1.0, 0.0,
        Tx, Ty, Tz, 1.0
    ]);
    // console.log(vertices)
    // 创建缓存
    var buffer = gl.createBuffer(); // 为顶点创建的缓存
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer); // 绑定缓冲区
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
    gl.vertexAttribPointer(vPosition, 4, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(vPosition);

    gl.uniform4f(u_FragColor, colors[1][0], colors[1][1], colors[1][2], colors[1][3]);
    gl.uniformMatrix4fv(u_transMat, false, mat4);

    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES, 0, ms * 3);

    canvas.onmousedown = function (ev) {
        // click(ev, gl, canvas, vPosition)
        getFocus(ev, gl, canvas, u_FragColor);
    }
    canvas.onmousemove = function (ev) {
        move(ev, gl, u_FragColor, u_transMat, vPosition);
    }
    canvas.onmouseup = function () {
        loseFocus(gl, u_FragColor);
    }
};

// 更新数据缓冲
function UpdateArrayBuffer(gl, u_FragColor, u_transMat, vPosition) {
    var vertices = getCircleVertex(r, ms, c);

    var Tx = center[0];
    var Ty = center[1];
    var Tz = 0.0;
    mat4 = new Float32Array([
        0.0, 1.0, 0.0, 0.0,
        -1.0, 0.0, 0.0, 0.0,
        0.0, 0.0, 1.0, 0.0,
        Tx, Ty, Tz, 1.0
    ]);
    // console.log(vertices)
    // 创建缓存
    var buffer = gl.createBuffer(); // 为顶点创建的缓存
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer); // 绑定缓冲区
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
    gl.vertexAttribPointer(vPosition, 4, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(vPosition);

    gl.uniform4f(u_FragColor, colors[1][0], colors[1][1], colors[1][2], colors[1][3]);
    gl.uniformMatrix4fv(u_transMat, false, mat4);

    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES, 0, ms * 3);
}

// 鼠标抬起时失去焦点
function loseFocus(gl, a_Color) {
    IsFocus = false;
}

// 鼠标按下时获取焦点
function getFocus(ev, gl, canvas, a_Color) {
    let xy = getCursorPos(ev)
    let x = xy[0]
    let y = xy[1]
    if (Math.pow(x-center[0],2)+Math.pow(y-center[1], 2) <= Math.pow(r, 2)){
        switch (c){
            case 90:  if (x - center[0] <0&&y-center[1]>0){
                space = calculateCircleSpace(x,y,ev)
                IsFocus = true;
            }
            break;

            default: break;
        }

    }
}

// 鼠标移动时根据IsFocus来判断是否需要移动
function move(ev, gl, u_FragColor, u_transMat, vPosition) {
    if (IsFocus){
        let xy = getCursorPos(ev);
        let x = xy[0];
        let y = xy[1];
        center[0] = x - space[0];
        center[1] = y - space[1];
        UpdateArrayBuffer(gl,u_FragColor, u_transMat, vPosition)
    }
}

// 计算鼠标点击的点到圆心的间距
function calculateCircleSpace(x, y, ev) {
    return vec2(x - center[0], y - center[1])
}

// 获取光标位置
function getCursorPos(ev) {
    let x = ev.clientX;
    let y = ev.clientY;
    // 返回值是一个 DOMRect 对象，这个对象是由该元素的 getClientRects() 方法返回的一组矩形的集合，就是该元素的 CSS 边框大小。
    // 返回的结果是包含完整元素的最小矩形，并且拥有left, top, right, bottom, x, y, width,
    // 和 height这几个以像素为单位的只读属性用于描述整个边框。除了width 和 height 以外的属性是相对于视图窗口的左上角来计算的
    let rect = ev.target.getBoundingClientRect();
    x = x - rect.left
    y = y - rect.top
    x = -1.0 + x / (canvas.width / 2);
    y = 1.0 - y / (canvas.height / 2);
    return vec2(x, y)
}
